<template>
  <div>
    <!-- 弹窗提示 -->
    <el-dialog v-model="dialog.isdialog">
      <el-card>
        <h3>{{ dialog.title }}</h3>
        <p>{{ dialog.content }}</p>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog.isdialog = false">取 消</el-button>
          <el-button type="primary" @click="dialog.isdialog = false">确 定</el-button>
        </div>
      </el-card>
    </el-dialog>
  </div>

  <!-- 编辑器区域 -->
  <el-container>
    <el-header>编辑</el-header>
    <el-main>
      <el-form :model="post" ref="postForm" @submit.native.prevent="submitPost" enctype="multipart/form-data">
        <!-- 标题输入框 -->
        <el-form-item label="标题" prop="title">
          <el-input v-model="post.title"></el-input>
        </el-form-item>

        <!-- 图片上传 -->
        <el-upload action="/file/upload/file" :on-success="handleUploadSuccess" :before-upload="beforeImageUpload"
          :auto-upload="true" class="upload-demo">
          <el-button slot="trigger">插图上传</el-button>
          <template #tip>仅支持jpg/png格式，大小不超过2MB。</template>
        </el-upload>

        <!-- 内容输入框 -->
        <div class="article-content">
          <el-form-item label="内容" prop="content" class="editer-style">
            <el-input type="textarea" :rows="20" resize="both" v-model="post.content" class="edit-content"
              @input="updateMarkdownPreview"></el-input>
          </el-form-item>
          <!-- Markdown预览区域 -->
          <el-container class="editer-style">
            <p style="margin: 0 0 0 1rem;">Markdown效果</p>
            <!-- <h3 style="margin: .1rem 0 .1rem 1rem;">{{ post.title }}</h3> -->
            <div id="markdownPreview" class="edit-content" v-html="convertToHtml(post.content)"></div>

          </el-container>
        </div>

        <!-- 封面图片上传 -->
        <!-- <el-form-item>
          <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload">
            <img v-if="post.coverImage" :src="post.coverImage" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon">封面</i>
          </el-upload>
        </el-form-item> -->

        <!-- 提交按钮 -->
        <!-- <el-form-item> -->
        <el-button type="primary" native-type="submit" style="margin-left: 1rem;">提交</el-button>
        <!-- </el-form-item> -->
      </el-form>
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import MarkdownIt from 'markdown-it';
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { useUserStore } from '@/stores/user';
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();
const md = new MarkdownIt();

// 对话框控制对象
const dialog = ref({
  title: '',
  content: '',
  isdialog: false,
});

// 获取登录用户ID
const user = useUserStore();
const my_id = user.loginstatus ? user.userInfo.id : -1;

// 提交表单数据
const post = ref({
  title: '',
  content: '',
  coverImageUrl: '',
  bookId: route.params.id,
});

// 处理图片上传成功
const handleUploadSuccess = (response: any) => {
  if (response && response.path) {
    const markdownImage = `\n![图片描述](${response.path})\n`;
    post.value.content += markdownImage;
  } else {
    ElMessage.error('图片上传成功，但未返回预期的URL');
  }
};

// 图片上传前的检查
const beforeImageUpload = (rawFile: File) => {
  return true;
};

// Markdown内容转HTML
const convertToHtml = (content: string) => {
  return md.render(content);
};

// 提交表单
function submitPost() {
  const formData = post.value;


  axios.post('/api/chapters/create', formData)
    .then(res => {
      dialog.value.title = '提示';
      dialog.value.content = '提交成功';
      dialog.value.isdialog = true;
      window.location.href = "/chapter_read/" + res.data.data.id;
    })
    .catch(() => {
      dialog.value.title = '提示';
      dialog.value.content = '提交失败';
      dialog.value.isdialog = true;
    });
}

// 更新Markdown预览
function updateMarkdownPreview() {
  // 在内容输入时实时更新Markdown预览
}

// 上传封面图片前的检查
function beforeAvatarUpload(file: File) {
  const isJPG = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG || !isLt2M) {
    return false;
  }

  // 执行上传操作
  post.value.coverImage = put('image', file);

  if (post.value.coverImage === 'error') {
    dialog.value.title = '提示';
    dialog.value.content = '上传失败';
    dialog.value.isdialog = true;
  }
}

// 上传封面图片
function put(filetype: string, file: File) {

  const formData = new FormData();
  formData.append('file', file);
  const fileurl = ref('');
  axios.post(`/file/upload/file`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',

    },
  }).then((res) => {
    fileurl.value = res.data.path;
  }).catch(() => {
    fileurl.value = 'error';
  });

  return fileurl.value;
}
</script>

<style scoped>
/* 头像上传区域样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 100px;
  height: 100px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

/* 文本区域样式 */
.resizable-textarea {
  resize: both;
  overflow: auto;
  min-width: 300px;
  min-height: 100px;
}

.article-content {
  display: flex;
  overflow: hidden;
}


.editer-style {
  display: inline-block;
  width: 42vw;
}


.edit-content {
  overflow: auto;
  height: 60vh;
}


.edit-content:last-child {
  margin-left: 1rem;
}
</style>
